<template>
  <div>
    <NormalForm pageTitle="来源管理" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt"
      @handleQuery="handleQuery" @handleReset="handleReset" @selectChange="selectChange"></NormalForm>
    <div class="g-card">
      <div style="text-align: right; padding: 20px 20px 20px 0;">
        <el-button icon="el-icon-plus" type="primary" v-hasPermi="['config:manage:add']" @click="createSource">创建来源</el-button>
      </div>
      <!-- 表格 -->
      <div style="padding: 0 20px 20px 20px">
        <el-table v-loading="loading" :data="tableList" style="width: 100%" height="415">
          <el-table-column type="index" width="55" align="center" label="序号" />
          <el-table-column label="来源ID" align="center" prop="sourceId" show-overflow-tooltip></el-table-column>
          <el-table-column label="业务条线" align="center" prop="scrmBussLineName" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="获客平台" align="center" prop="scrmGetGuestPlatName" show-overflow-tooltip width="160px" />
          <el-table-column label="获客来源" align="center" prop="scrmGetGuestSourceName" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="类型" align="center" prop="type" width="160px">
            <template slot-scope="{ row }">
              <div>
                <span v-if="row.type == '0'">新增</span>
                <span v-else-if="row.type == '1'">内置</span>
                <span v-else>-</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createBy">
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime">
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" :width="160">
            <template slot-scope="scope">
              <div class="option-span">
                <el-button type="text" size="small" v-hasPermi="['config:manage:edit']" @click="editSource(scope.row)"
                  :disabled="+scope.row.isRegular === 1">编辑</el-button>
                <el-button type="text" size="small" :disabled="+scope.row.isRegular === 1"
                  v-hasPermi="['config:manage:stop']" v-if="scope.row.state === '0'"
                  @click="stopUsing(scope.row)">停用</el-button>
                <el-button type="text" size="small" :disabled="+scope.row.isRegular === 1"
                  v-hasPermi="['config:manage:stop']" v-if="scope.row.state === '1'"
                  @click="stopUsing(scope.row)">恢复</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
          @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
    </div>
    <!-- 创建来源弹窗 -->
    <el-dialog :title="remark" :visible.sync="modifyVisible" width="520">
      <el-form :model="modifyForm" :rules="rules" ref="modifyForm">
        <el-form-item label="业务条线" prop="scrmBussLineId" label-width="90px">
          <el-select filterable v-model="modifyForm.scrmBussLineId" placeholder="请选择业务条线" style="width: 100%">
            <el-option v-for="item in enumOpt.bussinessList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="获客平台" prop="scrmGetGuestPlatName" label-width="90px">
          <el-input v-model="modifyForm.scrmGetGuestPlatName" placeholder="请输入获客平台" clearable style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="获客来源" prop="scrmGetGuestSourceName" label-width="90px">
          <el-input v-model="modifyForm.scrmGetGuestSourceName" placeholder="请输入获客来源" clearable style="width: 100%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="bottomBox">
        <el-button type="primary" @click="saveModify" :loading="saveLoading">确 认
        </el-button>
        <el-button class="button" @click="cancelModify">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSource, addUserPlat, addUserSource, editSource, getPlat, getSource, queryTaskList, stopSource } from '@/api/sourceManage/sourceManage'

export default {
  name: 'sourceManage',
  data() {
    return {
      queryForm: {
        scrmBussLineId: null,
        scrmGetGuestPlatId: null,
        scrmGetGuestSourceId: null,
        weUserId: '',
        pageNum: 1,
        pageSize: 20,
      },
      formList: [
        {
          label: '业务线条',
          value: '',
          prop: 'scrmBussLineId',
          type: 'SELECT',
          emunName: 'bussinessList',
          about: 'scrmGetGuestPlatId'
        },
        {
          label: '获客平台',
          value: '',
          prop: 'scrmGetGuestPlatId',
          type: 'SELECT',
          emunName: 'platformList',
          about: 'scrmGetGuestSourceId'
        },
        {
          label: '获客来源',
          value: '',
          prop: 'scrmGetGuestSourceId',
          type: 'SELECT',
          emunName: 'sourceList'
        },
        {
          label: '创建人',
          value: '',
          prop: 'weUserId',
          type: 'STAFF',
          emunName: ''
        },
      ],
      enumOpt: {
        bussinessList: [],
        platformList: [],
        sourceList: []
      },
      bussinessOpt: {},
      loading: false,
      total: 0,
      tableList: [],
      // =================================
      remark: '创建来源',
      modifyForm: {
        scrmBussLineId: '',
        scrmGetGuestPlatName: '',
        scrmGetGuestSourceName: ''
      },
      saveLoading: false,
      modifyVisible: false,
      rules: {
        scrmBussLineId: [
          { required: true, message: '请选择业务条线', trigger: 'change' }
        ],
        scrmGetGuestPlatName: [
          { required: true, message: '请输入获客平台', trigger: 'blur' }
        ],
        scrmGetGuestSourceName: [
          { required: true, message: '请输入获客来源', trigger: 'blur' }
        ]
      },
      rowContent: null,
    }
  },
  created() {
    this.getBussinessList()
    this.handleQuery()
  },
  methods: {
    getBussinessList() {
      // 业务条线
      this.getDicts('insurance_type').then((res) => {
        if (res.code === 200) {
          this.enumOpt.bussinessList = res.data
          res.data.forEach(item => {
            this.bussinessOpt[item.dictValue] = item.dictLabel
          })
        }
      })
    },
    getPlatList() {
      this.enumOpt.platformList = []
      this.enumOpt.sourceList = []
      // 获客平台
      getPlat({ scrmBussLineId: this.queryForm.scrmBussLineId }).then((res) => {
        if (res.code == 200) {
          res.rows.forEach(item => {
            this.enumOpt.platformList.push({ dictLabel: item.scrmGetGuestPlatName, dictValue: item.scrmGetGuestPlatId });
          })
        }
      })
    },
    getSourceList() {
      this.enumOpt.sourceList = []
      // 获客来源
      getSource({ scrmGetGuestPlatId: this.queryForm.scrmGetGuestPlatId }).then((res) => {
        res.rows.forEach(item => {
          this.enumOpt.sourceList.push({
            dictValue: item.scrmGetGuestSourceId,
            dictLabel: item.scrmSourceName
          })
        })
      })
    },
    selectChange(val) {
      if (val === 'scrmGetGuestPlatId') {
        this.queryForm.scrmGetGuestPlatId = null
        this.queryForm.scrmGetGuestSourceId = null
        this.getPlatList()
      } else if (val === 'scrmGetGuestSourceId') {
        this.queryForm.scrmGetGuestSourceId = null
        this.getSourceList()
      }
    },
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.queryTaskListFn();
    },
    // 远程搜索任务名称 + 搜索
    queryTaskListFn() {
      this.loading = true;
      let params = {
        scrmBussLineId: this.queryForm.scrmBussLineId,
        scrmGetGuestPlatId: this.queryForm.scrmGetGuestPlatId,
        scrmGetGuestSourceId: this.queryForm.scrmGetGuestSourceId,
        weUserId: this.queryForm.weUserId + '',
        pageNum: this.queryForm.pageNum,
        pageSize: this.queryForm.pageSize,
      }
      queryTaskList(params).then((res) => {
        if (res.code === 200) {
          this.tableList = res.rows || []
          this.total = res.total || 0
        }
        this.loading = false;
      })
    },
    // 翻页
    handleSizeChange(val) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.queryTaskListFn()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.queryTaskListFn()
    },
    // 重置
    handleReset() {
      this.queryForm = {
        scrmBussLineId: null,
        scrmGetGuestPlatId: null,
        scrmGetGuestSourceId: null,
        weUserId: '',
        pageNum: 1,
        pageSize: 20,
      };
      this.queryTaskListFn();
    },
    // 创建来源
    createSource() {
      this.remark = '创建来源'
      this.modifyForm = {
        scrmBussLineId: '',
        scrmGetGuestPlatName: '',
        scrmGetGuestSourceName: ''
      };
      this.modifyVisible = true
      this.$nextTick(() => {
        this.$refs.modifyForm.clearValidate()
      })
    },
    // 编辑
    editSource(row) {
      console.log(row, '------------row')
      this.remark = '编辑来源'
      this.modifyForm.scrmBussLineId = row.scrmBussLineId + ''
      this.modifyForm.scrmGetGuestPlatName = row.scrmGetGuestPlatName
      this.modifyForm.scrmGetGuestSourceName = row.scrmGetGuestSourceName
      this.rowContent = row
      this.modifyVisible = true
    },
    // 停用
    stopUsing(row) {
      var text = ''
      if (row.state === '0') {
        text = '停用'
      } else if (row.state === '1') {
        text = '恢复'
      }
      this.$confirm('确认' + text + '该记录吗？', '停用确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        stopSource({
          scrmChnlConfigId: row.scrmChnlConfigId,
          state: row.state
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success(res.data)
            this.queryTaskList()
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    saveModify() {
      this.$refs.modifyForm.validate(async (valid) => {
        this.saveLoading = true
        if (valid) {
          const params = {
            type: '0',
            ...this.modifyForm
          }
          // 新增获客平台
          let datas = await addUserPlat({
            scrmBussLineId: this.modifyForm.scrmBussLineId,
            scrmGetGuestPlatName: this.modifyForm.scrmGetGuestPlatName
          })
          params.scrmGetGuestPlatId = datas.data.scrmGetGuestPlatId
          // 新增获客来源
          let datas11 = await addUserSource({
            scrmGetGuestPlatId: datas.data.scrmGetGuestPlatId,
            scrmSourceName: this.modifyForm.scrmGetGuestSourceName
          })
          params.scrmGetGuestSourceId = datas11.data.scrmGetGuestSourceId
          params.scrmBussLineName = this.bussinessOpt[this.modifyForm.scrmBussLineId]
          console.log(params, '-----------params')

          if (this.remark === '创建来源') {
            addSource(params).then((res) => {
              this.saveLoading = false
              if (res.code === 200) {
                this.$message.success(res.data)
                this.handleQuery()
              } else {
                this.$message.error(res.msg)
              }
              this.modifyVisible = false
            }).catch((err) => {
              this.saveLoading = false
            })
          } else {
            params.scrmChnlConfigId = this.rowContent.scrmChnlConfigId
            editSource(params).then((res) => {
              this.saveLoading = false
              if (res.code === 200) {
                this.$message.success(res.data)
                this.handleQuery()
              } else {
                this.$message.error(res.msg)
              }
              this.modifyVisible = false
            }).catch((err) => {
              this.saveLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    cancelModify() {
      this.modifyVisible = false
      this.$refs.modifyForm.resetFields()
    }
  }
}
</script>


<style lang="scss" scoped>
@import "../../../../styles/base.scss";

.bottomBox {
  display: flex;
  justify-content: flex-end;
}

.button {
  width: 64px;
  height: 34px;
}

.el-table::before {
  //去掉最下面的那一条线
  height: 0px;
}

::v-deep .el-table th.el-table__cell.is-leaf,
.el-table td.el-table__cell {
  border-bottom: none !important;
}

::v-deep .el-table .el-table__header-wrapper th {
  background-color: #f8f8f9 !important;
}
</style>
